package com.njym.java.security.app.rest;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradeRefundApplyModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.njym.java.security.app.alipay.AliPayProperties;
import com.njym.java.security.app.biz.*;
import com.njym.java.security.app.entity.*;
import com.njym.java.security.common.msg.ObjectRestResponse;
import com.njym.java.security.common.rest.BaseController;
import com.njym.java.security.common.tradeStatusConfig.AliTradeStatus;
import com.njym.java.security.common.util.ResponseUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.BufferedOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/paymentRecord")
public class PaymentRecordController extends BaseController<PaymentRecordBiz, PaymentRecord> {
	private static final Logger log = LoggerFactory.getLogger(PaymentRecordController.class);
	@Autowired
	private PlatformTransactionManager txManager;
	@Resource
	private CourseCatalogueBiz courseCatalogueBiz;

	@Autowired
	private AlipayClient alipayClient;
	@Autowired
	private FamilyUserBiz familyUserBiz;
	@Autowired
	private FamilyConfigBiz familyConfigBiz;
	@Autowired
	private UserBiz userBiz;
	@Autowired
	private AliPayProperties aliPayProperties;
	@Autowired
	private FamilyWalletRecordBiz familyWalletRecordBiz;
	@Autowired
	private IdentityApplyBiz identityApplyBiz;

	private final Log logger = LogFactory.getLog(FamilyWalletRecordController.class);

	/**
	 * 购买积分
	 */
	@RequestMapping(value = "/buyPoints", method = RequestMethod.GET)
	@ResponseBody
	public Object buyPoints(@NotBlank Integer userId, @NotBlank String userName, @NotBlank Double needToPay) {
		String outTradeNo = this.getRandomNo();
		AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
		AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
		model.setTimeoutExpress("10m");
		model.setTotalAmount(needToPay.toString());
		model.setSubject("购买积分");
		model.setOutTradeNo(outTradeNo);
		request.setBizModel(model);
		request.setReturnUrl(aliPayProperties.getIntegralNotifyUrl());
		request.setNotifyUrl(aliPayProperties.getIntegralNotifyUrl());
		//交易成功回调地址
		String sign;
		try {
			AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
			if (response.isSuccess()) {
				PaymentRecord paymentRecord = new PaymentRecord();
				paymentRecord.setChargeUserId(userId);
				paymentRecord.setChargeUserName(userName);
//				paymentRecord.setLessonId(lessonId);
				paymentRecord.setOutTradeNo(outTradeNo);
				paymentRecord.setTotalFee(needToPay);
				paymentRecord.setTradeType("APP");
				paymentRecord.setCreateDate(new Date());
				paymentRecord.setRecType(1);
//				paymentRecord.setAttr1(classId.toString());
//				paymentRecord.setAttr2(code);
				baseBiz.insert(paymentRecord);
				sign = response.getBody();
			} else {
				return new ObjectRestResponse<>().rel(false);
			}
		}
		catch (AlipayApiException e) {
			e.printStackTrace();
			return new ObjectRestResponse<>().rel(false);
		}
		// 创建订单，生成订单号给前台
		Map<String, String> map = new HashMap<>(2);
		map.put("sign", sign);
		map.put("outTradeNo", outTradeNo);
		return new ObjectRestResponse<>().rel(true).data(map);
	}


	/**
	 * 课程支付
	 *
	 * @param userId   用户Id
	 * @param lessonId 课程Id
	 * @return
	 */
	@RequestMapping(value = "/payForLesson", method = RequestMethod.GET)
	@ResponseBody
	public Object payForLesson(@NotBlank Integer userId, @NotBlank Integer lessonId, @NotBlank String userName,@NotBlank Integer classId, String code) {
		CourseCatalogue courseCatalogue = courseCatalogueBiz.selectById(lessonId);
		String outTradeNo = this.getRandomNo();
		AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
		AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
		model.setTimeoutExpress("10m");
		model.setTotalAmount(courseCatalogue.getPrice().toString());
		model.setSubject("购买" + courseCatalogue.getCourseName());
		model.setOutTradeNo(outTradeNo);
		request.setBizModel(model);
		request.setReturnUrl(aliPayProperties.getReturnUrl());
		request.setNotifyUrl(aliPayProperties.getReturnUrl());
		//交易成功回调地址
		String sign;
		try {
			AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
			if (response.isSuccess()) {
//			if(true){

				PaymentRecord paymentRecord = new PaymentRecord();
				paymentRecord.setChargeUserId(userId);
				paymentRecord.setChargeUserName(userName);
				paymentRecord.setLessonId(lessonId);
				paymentRecord.setOutTradeNo(outTradeNo);
				paymentRecord.setTotalFee(courseCatalogue.getPrice());
				paymentRecord.setTradeType("APP");
				paymentRecord.setCreateDate(new Date());
				paymentRecord.setRecType(1);
				paymentRecord.setAttr1(classId.toString());
				paymentRecord.setAttr2(code);
				baseBiz.insert(paymentRecord);
				sign = response.getBody();

			} else {
				return new ObjectRestResponse<>().rel(false);
			}
		}
		catch (AlipayApiException e) {
//		catch (Exception e){
			e.printStackTrace();
			return new ObjectRestResponse<>().rel(false);
		}
		// 创建订单，生成订单号给前台
		Map<String, String> map = new HashMap<>(2);
		map.put("sign", sign);
		map.put("outTradeNo", outTradeNo);
		return new ObjectRestResponse<>().rel(true).data(map);

	}



	@RequestMapping(value = "/getPayStatus", method = RequestMethod.GET)
	@ResponseBody
	public ObjectRestResponse payForLesson(@NotBlank String outTradeNo) {
		AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
		AlipayTradeAppPayModel alipayTradeAppPayModel = new AlipayTradeAppPayModel();
		alipayTradeAppPayModel.setOutTradeNo(outTradeNo);
		request.setBizModel(alipayTradeAppPayModel);
		String tradeNo = "";
		String values = "";
		try {
			AlipayTradeQueryResponse response = alipayClient.execute(request);
			if (AliTradeStatus.QUERY_SUCCESS.equals(response.getCode())) {
				switch (response.getTradeStatus()) {
					case AliTradeStatus.WAIT_BUYER_PAY:
						values = AliTradeStatus.WAIT_BUYER_PAY;
						break;
					case AliTradeStatus.TRADE_SUCCESS:
						values = AliTradeStatus.TRADE_SUCCESS;
						tradeNo = response.getTradeNo();
						//查询数据库
						updateTradeNo(outTradeNo, response.getTradeNo());
						break;
					case AliTradeStatus.TRADE_CLOSED:
						break;
					case AliTradeStatus.TRADE_FINISHED:
						values = AliTradeStatus.TRADE_FINISHED;
						tradeNo = response.getTradeNo();
						updateTradeNo(outTradeNo, response.getTradeNo());
						break;
					default:
						values = AliTradeStatus.QUERY_FAILURE;
				}
			} else {
				log.info(response.getMsg());
			}
		}
		catch (AlipayApiException e) {
			e.printStackTrace();
			values = AliTradeStatus.QUERY_FAILURE;
		}
		Map<String, String> map = new HashMap<>(2);
		map.put("status", values);
		map.put("tradeNo", tradeNo);
		return new ObjectRestResponse().rel(true).data(map);
	}

	private void updateTradeNo(String outTradeNo, String tradeNo) {
		PaymentRecord paymentRecord = new PaymentRecord();
		paymentRecord.setOutTradeNo(outTradeNo);
		PaymentRecord businessRecord = baseBiz.selectOne(paymentRecord);
		if (businessRecord != null && StringUtils.isBlank(businessRecord.getTradeNo())) {
			businessRecord.setTradeStatus(AliTradeStatus.TRADE_SUCCESS);
			businessRecord.setTradeNo(tradeNo);
			businessRecord.setTradeDate(new Date());
			baseBiz.updateById(businessRecord);
		}
	}

	@RequestMapping(value = "/appTradeReturn")
	@ResponseBody
	public String appTradeReturn(HttpServletRequest request, HttpServletResponse response) throws Exception {
		log.info("有请求过来啦");
		String message = "";
		Map<String, String> params = new HashMap<>(16);
		Enumeration<String> parameterNames = request.getParameterNames();
		while (parameterNames.hasMoreElements()) {
			String parameterName = parameterNames.nextElement();
			params.put(parameterName, request.getParameter(parameterName));
		}
		//验证签名
		boolean signVerified = false;

		try {
			signVerified = AlipaySignature.rsaCheckV1(params, aliPayProperties.getAlipayPublicKey(), "UTF-8", aliPayProperties.getSignType());
		}
		catch (AlipayApiException e) {
		}

		if (signVerified) {
			// 若参数中的appid和填入的appid不相同，则为异常通知
			if (!aliPayProperties.getAppid().equals(params.get("app_id"))) {
				log.info("与付款时的appid不同，此为异常通知，应忽略！");
				message = "failed";
			} else {
				String outTradeNo = params.get("out_trade_no");
				log.info(outTradeNo + "号订单回调通知。");
				PaymentRecord paymentRecord1 = new PaymentRecord();
				paymentRecord1.setOutTradeNo(outTradeNo);
				PaymentRecord paymentRecord = baseBiz.selectOne(paymentRecord1);
				if (paymentRecord != null) {
					String status = params.get("trade_status");
					 if (AliTradeStatus.TRADE_SUCCESS.equals(status) || AliTradeStatus.TRADE_FINISHED.equals(status)) {
						// 如果状态是已经支付成功
						//成功 更新状态
						message = "success";
						String tradeNo = params.get("trade_no");
						paymentRecord.setTradeNo(tradeNo);
						paymentRecord.setTradeDate(new Date());
						paymentRecord.setTradeStatus(status);
						baseBiz.updateById(paymentRecord);
						//@TODO APP服务器状态,返回支付结果与tradeNo

						 //根绝 订单号 查询 记录
					     String 	classId = paymentRecord.getAttr1();
						 String 	code = paymentRecord.getAttr2();
						 //开始插入数据
						 DefaultTransactionDefinition def = new DefaultTransactionDefinition();
						 def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
						 TransactionStatus statuss = txManager.getTransaction(def);
						 try {
							 //购买课程后返金币和积分
							 //365课程
							 if(classId.equals("6")  || classId.equals("5") ){

								 //账号判断是否有代理
								 Example example = new Example(FamilyUser.class);
								 example.createCriteria().andEqualTo("id", paymentRecord.getChargeUserId());
								 List<FamilyUser> user = familyUserBiz.selectByExample(example);

								 //不是代理时购买365自动成为教育专员
								 if(!user.get(0).getFuserId().equals(user.get(0).getBaseId())){
									 IdentityApply identityApply = new IdentityApply();
									 identityApply.setUserId(user.get(0).getId());
									 identityApply.setMobile(user.get(0).getMobile());
									 identityApply.setName(user.get(0).getName());
									 identityApply.setEmail(user.get(0).getEmail());
									 identityApply.setStatus(2);

									 //如果未有课程码  则生成


									 if(user.get(0).getCourseCode() == null || "".equals(user.get(0).getCourseCode())){
										 //生成邀请码并判断是否重复
										 for(int i = 0; ; i ++) {
											 String codes = "K" + genRandomNum();
											 Example example8 = new Example(FamilyUser.class);
											 example8.createCriteria().andEqualTo("courseCode", codes);
											 List<FamilyUser> fu = familyUserBiz.selectByExample(example8);
											 if (fu.size() == 0) {
												 user.get(0).setCourseCode(codes);
												 break;
											 }
										 }
										 familyUserBiz.updateSelectiveById(user.get(0));

									 }

									 identityApplyBiz.insert(identityApply);
								 }


								 //若无代理  则不进行分账
								 if(user.get(0).getTeacherId() != null){
									 //获得代理信息  分账
									 Example example1 = new Example(User.class);
									 example1.createCriteria().andEqualTo("id", user.get(0).getTeacherId());
									 List<User> baseuser = userBiz.selectByExample(example1);
									 //判断代理是否开启
									 if("1".equals(baseuser.get(0).getAttr5())) {
										 //前一百个全额返还
										 Integer num = Integer.parseInt(baseuser.get(0).getAttr7());
										 if (num < 100) {
											 //修改金币和推广人数
											 User buser = baseuser.get(0);
											 Double price = Double.parseDouble(buser.getAttr6()) + paymentRecord.getTotalFee();
											 Integer n = num + 1;
											 buser.setAttr6(price.toString());
											 buser.setAttr7(n.toString());
											 userBiz.updateById(buser);
											 //添加分账记录
											 FamilyWalletRecord familyWalletRecord = new FamilyWalletRecord();
											 familyWalletRecord.setUserId(paymentRecord.getChargeUserId());
											 familyWalletRecord.setMechaismId(buser.getId());
											 familyWalletRecord.setType(1);
											 familyWalletRecord.setActualPayment(paymentRecord.getTotalFee());
											 familyWalletRecord.setRecordSn("代理全额返金币");
											 familyWalletRecord.setModifyTime(new Date());
											 familyWalletRecord.setCourseId(paymentRecord.getLessonId());
											 familyWalletRecord.setClassId(Integer.parseInt(classId));
											 familyWalletRecordBiz.insert(familyWalletRecord);
										 } else {
											 //大于100人 分45.3%
											 //修改金币和推广人数
											 User buser = baseuser.get(0);
											 Double price = Double.parseDouble(buser.getAttr6()) + paymentRecord.getTotalFee() * 0.453;
											 Integer n = num + 1;
											 buser.setAttr6(price.toString());
											 buser.setAttr7(n.toString());
											 userBiz.updateById(buser);
											 //添加分账记录
											 FamilyWalletRecord familyWalletRecord = new FamilyWalletRecord();
											 familyWalletRecord.setUserId(paymentRecord.getChargeUserId());
											 familyWalletRecord.setMechaismId(buser.getId());
											 familyWalletRecord.setType(1);
											 familyWalletRecord.setRecordSn("代理返45.3%金币");
											 familyWalletRecord.setModifyTime(new Date());
											 familyWalletRecord.setCourseId(paymentRecord.getLessonId());
											 familyWalletRecord.setClassId(Integer.parseInt(classId));
											 familyWalletRecord.setActualPayment(paymentRecord.getTotalFee() * 0.453);
											 familyWalletRecordBiz.insert(familyWalletRecord);
										 }
									 }else{

									 }
								 }else{

								 }

							 }
							 //520课程
							 else if(classId.equals("7")){
								 if(code != null && code != "" && !"undefined".equals(code)) {
									 //判断邀请码是否正确
									 Example example = new Example(FamilyUser.class);
									 example.createCriteria().andEqualTo("courseCode", code);
									 List<FamilyUser> user = familyUserBiz.selectByExample(example);
									 //有教育专员
									 if (user.size() > 0) {
										 //教育专员分19.3%
										 FamilyUser fu = user.get(0);
										 Double price = fu.getPrice() + paymentRecord.getTotalFee() * 0.193;
										 fu.setPrice(price);
										 //分金币
										 familyUserBiz.updateById(fu);
										 //添加记录
										 FamilyWalletRecord familyWalletRecord = new FamilyWalletRecord();
										 familyWalletRecord.setUserId(paymentRecord.getChargeUserId());
										 familyWalletRecord.setMechaismId(fu.getId());
										 familyWalletRecord.setType(5);
										 familyWalletRecord.setRecordSn("教育专员返19.3%金币");
										 familyWalletRecord.setModifyTime(new Date());
										 familyWalletRecord.setCourseId(paymentRecord.getLessonId());
										 familyWalletRecord.setClassId(Integer.parseInt(classId));
										 familyWalletRecord.setActualPayment(paymentRecord.getTotalFee() * 0.193);
										 familyWalletRecordBiz.insert(familyWalletRecord);

										 //判断是否有代理
										 Example example1 = new Example(FamilyUser.class);
										 example1.createCriteria().andEqualTo("id", paymentRecord.getChargeUserId());
										 List<FamilyUser> users = familyUserBiz.selectByExample(example1);
										 //代理分42.4%
										 if (users.get(0).getTeacherId() != null) {
											 //获得代理信息  分账
											 Example example2 = new Example(User.class);
											 example2.createCriteria().andEqualTo("id", users.get(0).getTeacherId());
											 List<User> baseuser = userBiz.selectByExample(example2);
											 //判断代理是否开启
											 if("1".equals(baseuser.get(0).getAttr5())) {
												 User buser = baseuser.get(0);

												 Double p = Double.parseDouble(buser.getAttr6()) + paymentRecord.getTotalFee() * 0.424;

												 buser.setAttr6(p.toString());

												 userBiz.updateById(buser);
												 //添加分账记录
												 FamilyWalletRecord familyWalletRecords = new FamilyWalletRecord();
												 familyWalletRecords.setUserId(paymentRecord.getChargeUserId());
												 familyWalletRecords.setMechaismId(buser.getId());
												 familyWalletRecords.setType(1);
												 familyWalletRecords.setActualPayment(paymentRecord.getTotalFee() * 0.424);
												 familyWalletRecords.setRecordSn("代理返42.4%金币");
												 familyWalletRecords.setModifyTime(new Date());
												 familyWalletRecords.setCourseId(paymentRecord.getLessonId());
												 familyWalletRecords.setClassId(Integer.parseInt(classId));
												 familyWalletRecordBiz.insert(familyWalletRecords);
											 }else{

											 }
										 } else {

										 }

									 } else {
										 //无教育专员
										 //判断是否有代理
										 Example example1 = new Example(FamilyUser.class);
										 example1.createCriteria().andEqualTo("id", paymentRecord.getChargeUserId());
										 List<FamilyUser> users = familyUserBiz.selectByExample(example1);
										 //代理分42.4%
										 if (users.get(0).getTeacherId() != null) {
											 //获得代理信息  分账
											 Example example2 = new Example(User.class);
											 example2.createCriteria().andEqualTo("id", users.get(0).getTeacherId());
											 List<User> baseuser = userBiz.selectByExample(example2);
											 //判断代理是否开启
											 if("1".equals(baseuser.get(0).getAttr5())) {
												 User buser = baseuser.get(0);

												 Double p = Double.parseDouble(buser.getAttr6()) + paymentRecord.getTotalFee() * 0.424;

												 buser.setAttr6(p.toString());

												 userBiz.updateById(buser);
												 //添加分账记录
												 FamilyWalletRecord familyWalletRecords = new FamilyWalletRecord();
												 familyWalletRecords.setUserId(paymentRecord.getChargeUserId());
												 familyWalletRecords.setMechaismId(buser.getId());
												 familyWalletRecords.setType(1);
												 familyWalletRecords.setActualPayment(paymentRecord.getTotalFee() * 0.424);
												 familyWalletRecords.setRecordSn("代理返42.4%金币");
												 familyWalletRecords.setModifyTime(new Date());
												 familyWalletRecords.setCourseId(paymentRecord.getLessonId());
												 familyWalletRecords.setClassId(Integer.parseInt(classId));
												 familyWalletRecordBiz.insert(familyWalletRecords);
											 }else{

											 }
										 } else {

										 }
									 }
								 }
							 }
						 }catch (Exception ex) {
							 txManager.rollback(statuss);
							 log.error("网络连接超时", ex);
							 AlipayTradeRefundApplyModel alipayTradeRefundApplyModel = new AlipayTradeRefundApplyModel();
							 alipayTradeRefundApplyModel.setOutTradeNo(outTradeNo);
							 alipayTradeRefundApplyModel.setRefundAmount(paymentRecord.getTotalFee().toString());

							 alipayTradeRefundApplyModel.setOutRequestNo("R" + getRandomNo());

							 AlipayTradeRefundRequest alipayTradeRefundRequest = new AlipayTradeRefundRequest();
							 alipayTradeRefundRequest.setBizModel(alipayTradeRefundApplyModel);

							 AlipayTradeRefundResponse responses = alipayClient.execute(alipayTradeRefundRequest,"",aliPayProperties.getAppAuthToken());

						 }
						 txManager.commit(statuss);







					 } else {
						message = "failed";
						log.info("订单状态未知！");
					}
				} else {
					message = "failed";
					log.info("此单不存在！");
				}
			}
		} else {
			// 如果验证签名没有通过
			message = "failed";
			log.info("验证签名失败！");
		}
		BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
		out.write(message.getBytes());
		out.flush();
		out.close();
		return message;
	}

    @RequestMapping(value = "/integralNotify")
    @ResponseBody
    public String integralNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("有请求过来啦");
        String message = "";
        Map<String, String> params = new HashMap<>(16);
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String parameterName = parameterNames.nextElement();
            params.put(parameterName, request.getParameter(parameterName));
        }
        //验证签名
        boolean signVerified = false;

        try {
            signVerified = AlipaySignature.rsaCheckV1(params, aliPayProperties.getAlipayPublicKey(), "UTF-8", aliPayProperties.getSignType());
        }
        catch (AlipayApiException e) {
        }

        if (signVerified) {
            // 若参数中的appid和填入的appid不相同，则为异常通知
            if (!aliPayProperties.getAppid().equals(params.get("app_id"))) {
                log.info("与付款时的appid不同，此为异常通知，应忽略！");
                message = "failed";
            } else {
                String outTradeNo = params.get("out_trade_no");
                log.info(outTradeNo + "号订单回调通知。");
                PaymentRecord paymentRecord1 = new PaymentRecord();
                paymentRecord1.setOutTradeNo(outTradeNo);
                PaymentRecord paymentRecord = baseBiz.selectOne(paymentRecord1);
                if (paymentRecord != null) {
                    String status = params.get("trade_status");
                    if (AliTradeStatus.TRADE_SUCCESS.equals(status) || AliTradeStatus.TRADE_FINISHED.equals(status)) {
                        // 如果状态是已经支付成功
                        //成功 更新状态
                        message = "success";
                        String tradeNo = params.get("trade_no");
                        paymentRecord.setTradeNo(tradeNo);
                        paymentRecord.setTradeDate(new Date());
                        paymentRecord.setTradeStatus(status);
                        baseBiz.updateById(paymentRecord);
                        //@TODO APP服务器状态,返回支付结果与tradeNo

                        //根据 订单号 查询 记录
                        Integer userId = paymentRecord.getChargeUserId();
                        Double fee = paymentRecord.getTotalFee()*10;
                        Integer point = fee.intValue();
                        //开始插入数据，开启事务
                        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
                        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
                        TransactionStatus statuss = txManager.getTransaction(def);
                        try {
                            //给用户添加积分，在记录表中添加流水明细
                            FamilyUser user = familyUserBiz.selectById(userId);
                            FamilyWalletRecord entity = new FamilyWalletRecord();
                            entity.setUserId(userId);
                            entity.setMechaismId(userId);
                            entity.setModifyTime(new Date());
                            entity.setType(6);
                            entity.setDetail(point);
                            entity.setRecordSn("购兑积分");
                            entity.setLeftPoints(user.getIntegral() + point);
                            familyWalletRecordBiz.insert(entity);
                            familyUserBiz.updateUserPoints(userId, point);

                        }catch (Exception ex) {
                            txManager.rollback(statuss);
                            log.error("网络连接超时", ex);
                            AlipayTradeRefundApplyModel alipayTradeRefundApplyModel = new AlipayTradeRefundApplyModel();
                            alipayTradeRefundApplyModel.setOutTradeNo(outTradeNo);
                            alipayTradeRefundApplyModel.setRefundAmount(paymentRecord.getTotalFee().toString());

                            alipayTradeRefundApplyModel.setOutRequestNo("R" + getRandomNo());

                            AlipayTradeRefundRequest alipayTradeRefundRequest = new AlipayTradeRefundRequest();
                            alipayTradeRefundRequest.setBizModel(alipayTradeRefundApplyModel);

                            AlipayTradeRefundResponse responses = alipayClient.execute(alipayTradeRefundRequest,"",aliPayProperties.getAppAuthToken());

                        }
                        txManager.commit(statuss);







                    } else {
                        message = "failed";
                        log.info("订单状态未知！");
                    }
                } else {
                    message = "failed";
                    log.info("此单不存在！");
                }
            }
        } else {
            // 如果验证签名没有通过
            message = "failed";
            log.info("验证签名失败！");
        }
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        out.write(message.getBytes());
        out.flush();
        out.close();
        return message;
    }

	@RequestMapping(value = "/getPayment", method = RequestMethod.GET)
	@ResponseBody
	public Object getPayment(@NotBlank String userId){
		List<PaymentRecordVo> payments = baseBiz.getPayment(userId);

		List<Integer> ids = new ArrayList();
		List<CourseCatalogue> list = new ArrayList<>();
		if (payments.size() > 0) {
			payments.forEach(item ->{
				ids.add(item.getLessonId());
			});
			Example example = new Example(CourseCatalogue.class);
			example.createCriteria().andIn("id",ids);
			list = courseCatalogueBiz.selectByExample(example);
		}
		Map<String,Object> data = new HashMap<>(2);
		data.put("payments",payments);
		data.put("list",list);
		return new ObjectRestResponse<>().rel(true).data(data);
	}

	@RequestMapping(value = "/getCourseStatus", method = RequestMethod.GET)
	@ResponseBody
	public Object getCourseStatus(@NotBlank String userId,@NotBlank String courseId){
		if (!userId.equals("undefined") && !courseId.equals("undefined")) {
			Example example = new Example(PaymentRecord.class);
			example.createCriteria().andEqualTo("chargeUserId",Integer.parseInt(userId)).andEqualTo("lessonId",Integer.parseInt(courseId)).andIsNotNull("tradeNo");
			List<PaymentRecord> list=baseBiz.selectByExample(example);
			if(list.size()>0){
				return new ObjectRestResponse<>().rel(true);
			}else {
				return new ObjectRestResponse<>().rel(false);
			}
		} else {
			return ResponseUtil.fail(40301, "错误！");
		}

	}

	private String getRandomNo() {

		SimpleDateFormat simpleDateFormat;

		simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

		Date date = new Date();

		String str = simpleDateFormat.format(date);

		Random random = new Random();
		// 获取5位随机数
		int rannum = (int)(random.nextDouble() * (99999 - 10000 + 1)) + 10000;
		// 当前时间
		return str + rannum;
	}

	/**
	 * 生成邀请码
	 * @return
	 */
	public String genRandomNum(){
		int  maxNum = 36;
		int i;
		int count = 0;
		char[] str = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K',
			'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
			'X', 'Y', 'Z',  '2', '3', '4', '5', '6', '7', '8', '9' };
		StringBuffer pwd = new StringBuffer("");
		Random r = new Random();
		while(count < 5){
			i = Math.abs(r.nextInt(maxNum));
			if (i >= 0 && i < str.length) {
				pwd.append(str[i]);
				count ++;
			}
		}
		return pwd.toString();
	}
}